package com.wondertek.mist;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.wondertek.mist.po.VersionPo;
import com.wondertek.mist.utils.AntiHijackingUtils;
import com.wondertek.mist.utils.ApkUpdate;
import com.wondertek.mist.utils.DialogHelper;
import com.wondertek.mist.utils.NetworkUtil;
import com.wondertek.mist.utils.RUtil;
import com.wondertek.mist.utils.StringUtils;

public class StartActivity extends Activity {

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Utils.MSG_TO_MIST:
				toMistAction();
				break;
			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		LinearLayout startLayout = (LinearLayout) getLayoutInflater().inflate(
				RUtil.layout(this, "start"), null);

		String bg = Utils.getMetaValue(this, "mist.background");
		if (StringUtils.isBlank(bg)) {
			bg = "start_bg";
		}

		startLayout.setBackgroundResource(RUtil.drawable(this, bg));

		setContentView(startLayout);

		String checkUpdateUrl = Utils.getMetaValue(this, "mist.checkUpdateUrl");

		if (!NetworkUtil.isNetworkAvailable(this)) {
			DialogHelper.showToastCanceledOnTouchOutside(this, "提示",
					"网络异常，请检查网络设置后，重新启动应用");
		} else {
			if (StringUtils.isBlank(checkUpdateUrl)) {
				toMistAction();
			} else {
				checkUpdate(checkUpdateUrl);
			}

		}
	}

	// 只提供给车险正常启动，MAM跳转不从StartActivity走
	public void toMistAction() {
		Intent toMainIntent = new Intent(this, MistActivity.class);
		startActivity(toMainIntent);
		finish();

	}

	// 升级
	private void checkUpdate(final String updateUrl) {
		new AsyncTask<Void, Void, VersionPo>() {
			protected void onPreExecute() {
			}

			protected VersionPo doInBackground(Void... params) {
				HttpClient client = new DefaultHttpClient();
				client.getParams().setParameter(
						CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
				HttpGet get = new HttpGet(updateUrl);
				try {
					HttpResponse response = client.execute(get);
					HttpEntity entity = response.getEntity();
					String str = EntityUtils.toString(entity);
					JSONObject o = new JSONObject(str);
					VersionPo versionPo = new VersionPo();
					versionPo.setVersion_result(o.getString("result").trim());
					versionPo.setVersion_url(o.getString("url").trim());

					JSONArray content = o.getJSONArray("features");
					int length = content.length();
					if (length != 0) 
					{
						String[] features = new String[length];
						for (int i = 0; i < length; i++) {
							features[i] = (String) content.get(i);
						}
						versionPo.setVersion_features(features);
					} 
					else 
					{
						// /versionPo.setVersion_features(features);
					}
					return versionPo;
				} catch (Exception e) {

				} finally {
					try {
						client.getConnectionManager().shutdown();
					} catch (Exception ex) {
					}
				}
				return null;
			}

			protected void onPostExecute(final VersionPo versionPo) {
				if (versionPo != null) {
					String versionResult = versionPo.getVersion_result();
					// 0 不需要更新 1：选择更新 2 强制更新
					if ("0".equals(versionResult)) {
						toMistAction();

					} else {
						ApkUpdate.startUpdateProgress(StartActivity.this,
								versionPo, handler);
					}
				} else {
					toMistAction();
				}
			}
		}.execute();

	}

	@Override
	protected void onStop() {
		boolean safe = AntiHijackingUtils.checkActivity(this);
		if (!safe) {
			// 弹出警示信息
			Toast.makeText(getApplicationContext(), "您的界面被覆盖，请确认应用是否安全",
					Toast.LENGTH_SHORT).show();

		}
		super.onStop();
	}

}
